#!/bin/sh

e2e_test_install() {
  K8S_NODES=$(kubectl get nodes | tail -n+2 | wc -l)
  K8S_NODES=$(($K8S_NODES+ 1))
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" "$K8S_NODES"

  wait_pods_running "$CLUSTER_NAMESPACE" "1"
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
}

e2e_test() {
  run_test "Check anti affinity is blocking pod creation" test_anti_affinity_is_blocking_pod_creation
}

test_anti_affinity_is_blocking_pod_creation() {
  if wait_until -t "$((E2E_TIMEOUT * 4))" is_anti_affinity_blocking_pod_creation
  then
    echo "Cluster anti affinity is blocking pod creation"
  else
    echo "Cluster anti affinity isn't blocking pod creation"
    return 1
  fi
}

is_anti_affinity_blocking_pod_creation() {
  kubectl get events -n "$CLUSTER_NAMESPACE" \
    --template '{{ range .items }}{{ .reason }}/{{ .involvedObject.kind }}/{{ .involvedObject.name }}/{{ .message }}{{ printf "\n" }}{{ end }}' \
    | grep "^FailedScheduling/Pod/$CLUSTER_NAME-[1-9]\+/" \
    | grep -q "node(s) didn't match pod \(affinity/\)\?anti-affinity"
}
